package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.BackTimeDAO;
import mwa.cs.dao.ReceivePositionDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SitesDAO;
import mwa.cs.database.Database;
import mwa.cs.model.BackTime;
import mwa.cs.model.ReceivePosition;
import mwa.cs.util.JDate;

public class CS81000Srvl extends HttpServlet implements Servlet {
	
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;
	private Database db;

    public CS81000Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	String vaProcessType = request.getParameter("process_type");
    	
		if(vaProcessType.equals("getBackTime")){
			getBackTime(request,response);
		}
		else if (vaProcessType.equals("db")) {
			getDbStatus(request, response);
		}
		else
		{
			// insert / edit
			manageData(request,response);
		}
    }
    
    public void manageData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		this.db = new Database();
		JDate voJDate = new JDate();
		String vaDate = voJDate.getDate();
		String vaTime = voJDate.getTime();
		
		String vaBackTimeDate = request.getParameter("BACK_TIME_DATE");
		String vaExpireDate = request.getParameter("EXPIRE_DATE");
		
		BackTimeDAO voDao = new BackTimeDAO(db);
		
		BackTime voBackTime = new BackTime();
		voBackTime.setVnSiteId(vnSiteId);
		voBackTime.setVaBackTimeDate(vaBackTimeDate.replace("/", ""));
		voBackTime.setVaExpireDate(vaExpireDate.replace("/", ""));
		voBackTime.setVnInsertUserId(vnUserId);
		voBackTime.setVaInsertDate(vaDate);
		voBackTime.setVaInsertTime(vaTime);
		voBackTime.setVnUpdateUserId(vnUserId);
		voBackTime.setVaUpdateDate(vaDate);
		voBackTime.setVaUpdateTime(vaTime);
		
		boolean vbHasBackTime = voDao.hasBackTime(vnSiteId);
		boolean vaResult = false;
		
		try {	
			db.beginTransaction();
			if(vbHasBackTime)
				// Update
				vaResult = voDao.update(voBackTime);
			else
				// Add
				vaResult = voDao.insert(voBackTime);
		db.commit();
		} catch (Exception e) {
			db.rollback();
			SMErrorLogDAO.getInstance().addLog(0, "CS81000", JDate.getDate(), JDate.getTime(),vnUserId, "CS81000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			e.getMessage();
		}
		
		db.close();
		
		if(vaResult)
			response.getWriter().write("success");
		else
			response.getWriter().write("fail");
		
    }

    public void getBackTime(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voObject.put("status", "connect_db_fail");
			voOut.print(voObject.toJSONString());
			return;
		}
		
		BackTimeDAO voDao = new BackTimeDAO(db);
		BackTime voBackTime = voDao.getBackTime(vnSiteId);
		
		if(voBackTime != null)
		{	
			voObject.put("status", "true");
			voObject.put("vnSiteId", voBackTime.getVnSiteId());
			voObject.put("vaBackTimeDate", convertDateToSlash(voBackTime.getVaBackTimeDate()));
			voObject.put("vaExpireDate", convertDateToSlash(voBackTime.getVaExpireDate()));
			voObject.put("vnInsertUserId", voBackTime.getVnInsertUserId());
			voObject.put("vaInsertDate", voBackTime.getVaInsertDate());
			voObject.put("vaInsertTime", voBackTime.getVaInsertTime());
			voObject.put("vnUpdateUserId", voBackTime.getVnUpdateUserId());
			voObject.put("vaUpdateDate", voBackTime.getVaUpdateDate());
			voObject.put("vaUpdateTime", voBackTime.getVaUpdateTime());
		}
		else
		{
			voObject.put("status", "false");
		}
		
		db.close();
		
		voOut.print(voObject.toJSONString());
    }
    
    private String convertDateToSlash(String paDate)
    {
    	try
    	{
    		String vaDay = paDate.substring(0, 2);
    		String vaMonth = paDate.substring(2, 4);
    		String vaYear = paDate.substring(4, 8);
    		
    		return vaDay + "/" + vaMonth + "/" + vaYear;
    	}
    	catch(Exception ex)
    	{
    		return "";
    	}
    }
    
	public void getDbStatus(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");

		PrintWriter voOut = response.getWriter();

		try {
			this.db = new Database();
			db.close();
			voOut.print("success");
		} catch (Exception ex) {
			voOut.print("connect_db_fail");
		}
	}
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
}
